package com;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.util.EntityUtils;
import org.smartboot.http.HttpRequest;
import org.smartboot.http.HttpResponse;
import org.smartboot.http.enums.HttpStatus;
import org.smartboot.http.server.handle.HttpHandle;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpServiceHandle extends HttpHandle {

    private String targetUrl;

    public HttpServiceHandle(String targetUrl) {
        this.targetUrl = targetUrl;
    }

    @Override
    public void doHandle(HttpRequest request, HttpResponse response) throws IOException {
        if (StringUtils.isNotBlank(request.getQueryString())) {
            targetUrl += "?" + request.getQueryString();
        }
        CloseableHttpResponse clientResponseData = HttpUtils.doHttpProcess(request, targetUrl, new InputStreamEntity(request.getInputStream(), HttpUtils.getContentLength(request)));

        if (clientResponseData == null) {
            response.setHttpStatus(HttpStatus.NOT_FOUND);
            response.write(HttpStatus.NOT_FOUND.toString().getBytes());
        } else {
            Header[] headers = clientResponseData.getAllHeaders();
            for (Header header : headers) {
                String headerName = header.getName();
                if (headerName.equalsIgnoreCase("Last-Modified")) {
                    continue;
                }

                if (headerName.equalsIgnoreCase("ETag")) {
                    continue;
                }

                if (StringUtils.isBlank(response.getHeader(headerName))) {
                    response.setHeader(header.getName(), header.getValue());
                }
            }
            HttpEntity httpEntity = clientResponseData.getEntity();
            response.write(EntityUtils.toByteArray(httpEntity));
        }

    }

    public String getTargetUrl() {
        return targetUrl;
    }

    public void setTargetUrl(String targetUrl) {
        this.targetUrl = targetUrl;
    }
}
